#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtNetwork>
#include <QFileInfo>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
    manager->get(QNetworkRequest(QUrl("http://www.baidu.com"))); // 发送网络请求

    ui->progressBar->hide();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::replyFinished(QNetworkReply *reply)
{
    QString all = reply->readAll();
    ui->textBrowser->setText(all);
    reply->deleteLater(); // 删除reply对象
}

void MainWindow::startRequest(QUrl url)
{
    reply = manager->get(QNetworkRequest(url));
    connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDataReadProgress(qint64,qint64)));
    connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));
}

void MainWindow::httpReadyRead()
{
    if (file)
    {
        file->write(reply->readAll());
    }
}

void MainWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
    if (-1 == totalBytes)
    {
        return;
    }

    ui->progressBar->setMaximum(totalBytes);
    ui->progressBar->setValue(bytesRead);
}

void MainWindow::httpFinished()
{
    ui->progressBar->hide();

    file->flush();
    file->close();

    delete file;
    file = nullptr;

    reply->deleteLater();
    reply = nullptr;
}

void MainWindow::on_pushButton_clicked()
{
    url = ui->lineEdit->text(); // todo https下载
    QFileInfo fileInfo(url.path());
    QString fileName(fileInfo.fileName());

    file = new QFile(fileName);
    if (!file->open(QIODevice::WriteOnly))
    {
        qDebug() << "file error";
        delete file;
        file = nullptr;
        return;
    }

    startRequest(url);
    ui->progressBar->setValue(0);
    ui->progressBar->show();
}
